package controller;

import javafx.event.ActionEvent;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import model.dao.Database;
import view.AddGroupView;
import view.GMItemView;
import view.OnLineView;
import view.PBoxView;

import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AddGroupController {
    public ListView selectLV;
    public ListView selectedLV;
    public TextField groupTF;
    public AnchorPane addGroupPane;

    private List<String> list = new ArrayList<>();
//    private Vector<GMItemView> gmItemViews = new Vector<>();

    /**
     * 从左边列表选择群成员
     * @param mouseEvent
     */
    public void selectMember(MouseEvent mouseEvent) {
        Pane pane = (Pane) selectLV.getSelectionModel().selectedItemProperty().get();

        Label label = (Label)pane.lookup("#name");
        String nameAndAccount = label.getText();
        String account = nameAndAccount.split("\\(")[1].split("\\)")[0];

        boolean flag = true;
        for (String s : list) {
            if (s.equals(account)) {
                flag = false;
                break;
            }
            flag = true;
        }
        if (flag) {
            list.add(account);
            try {
                Database database = new Database();
                database.connect();
                String sql = "select portrait from `user` where account = ?";
                ResultSet resultSet = database.execResult(sql, account);
                String portrait = null;
                if (resultSet.next()) {
                    portrait = resultSet.getString("portrait");
                }
                GMItemView itemView = new GMItemView(nameAndAccount, portrait);
                selectedLV.getItems().add(itemView.getPane());
//                gmItemViews.add(itemView);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(list);
        }

    }

    /**
     * 选错了成员，从右边的列表删除改成员
     * @param mouseEvent
     */
    public void delMember(MouseEvent mouseEvent) {
        int index = selectedLV.getSelectionModel().getSelectedIndex();
        System.out.println(index);
        selectedLV.getItems().remove(index);
        list.remove(index);
    }

    /**
     * 点击创建，创建群聊，创建群聊前选检测是否填写所需数据
     * @param actionEvent
     */
    public void createGroup(ActionEvent actionEvent) {
        String groupName = groupTF.getText();
        if (groupName.isEmpty()) {
            try {
                new PBoxView("请填写群名！").show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            AddGroupView view = (AddGroupView) addGroupPane.getScene().getWindow();
            OnLineView onLineView = view.getOnLineView();
            list.add(onLineView.getYourAccount());
            System.out.println(groupName + "---" + list);
            Database database = new Database();
            database.connect();

            Random random = new Random(System.currentTimeMillis());
            int num = (int) ((random.nextDouble()*9 + 1) * 10000);
            int pic = random.nextInt(12) + 1;

            String groupAccount = String.valueOf(num);
            String groupPortrait = "css/img/head/" + pic + ".png";
            System.out.println(groupPortrait);
            String sql = "insert into `group`(group_name, group_portrait, group_account) values(?, ?, ?)";
            try {
                database.exec(sql, groupName, groupPortrait, groupAccount);
                ResultSet resultSet = database.execResult("select group_id from `group` where group_account = ?", groupAccount);
                String group_id = null;
                if (resultSet.next()) {
                    group_id = resultSet.getString("group_id");
                }
                resultSet.close();
                if (group_id != null) {
                    List<String> uids = new ArrayList<>();
                    for (String account : list) {
                        ResultSet resultSet1 = database.execResult("select user_id from `user` where account = ?", account);
                        if (resultSet1.next()) {
                            String user_id = resultSet1.getString("user_id");
                            String sql2 = "insert into `group_members`(group_id, user_id) values(?, ?)";
                            database.exec(sql2, group_id, user_id);
                            uids.add(user_id);
                        }
                        resultSet1.close();
                    }
                    String tip = "操作成功！\n" + "群名：" + groupName + "\n群号：" + groupAccount;
                    new PBoxView(tip).show();
                    onLineView.createNewGroup(groupName, groupPortrait, uids);

                    ((AddGroupView) addGroupPane.getScene().getWindow()).close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void cancel(ActionEvent actionEvent) {
        ((AddGroupView) addGroupPane.getScene().getWindow()).close();
    }
}
